<?php
class GoodsModule
{
	public function index()
	{
		global $_FANWE;

		$cache_args = array(
			'index',
			$_FANWE['cookie']['city_py'],
			intval($_FANWE['request']['site']),
			trim($_FANWE['request']['date']),
			intval($_FANWE['request']['cat']),
			trim($_FANWE['request']['sort']),
			trim($_FANWE['request']['prices']),
			$_FANWE['page']
		);

		$_FANWE['nav_title'] = lang('common','goods_index');

		$cache_file = getTplCache('page/goods_index',$cache_args);

		define('IS_CACHE_TPL',true);

		if(!@include($cache_file))
			GoodsModule::getList();

		display($cache_file);
	}

	public function search()
	{
		global $_FANWE;
		$_FANWE['nav_title'] = lang('common','goods_search');

		$page_args = array(
			'city_py' => CURRENT_CITY_PY,
			'sort' => trim($_FANWE['request']['sort']),
			'keyword' => trim($_FANWE['request']['keyword']),
		);

		$keyword = '';
		if(!empty($page_args['keyword']))
		{
			$page_args['keyword'] = urldecode($page_args['keyword']);
			$keyword = &$page_args['keyword'];

			$keyword_query = clearSymbol($page_args['keyword']);
			if(!empty($keyword_query))
			{
				$search_txt = clearRepeat($keyword_query);
				$keyword_query = segmentToUnicode($keyword_query,'+');
                $fields = ",MATCH (gm.content) AGAINST ('$keyword_query') AS similarity ";
				$where.=" WHERE MATCH (gm.content) AGAINST ('$keyword_query' IN BOOLEAN MODE)";
			}
			else
				$keyword = '';
		}

		if(!empty($keyword))
		{
			$insert_sort = 'gk.cr_sort ASC';

			$city_name = $_FANWE['current_city']['name'];

			if(CURRENT_CITY_PY == CHINA_CITY_PY)
			{
				//全国不包含所有城市商品时
				if($_FANWE['setting']['all_city'] == 0)
				{
					$where.=  " AND gk.city = '$city_name'";
				}
				else
					$insert_sort = 'gk.r_sort ASC';
			}
			elseif(CURRENT_CITY_PY != '')
			{
				//城市显示全国商品时
				if($_FANWE['setting']['index_all'] == 1)
				{
					$fields .= ",(gk.city = '$city_name') as is_now_city";
					$insert_sort = 'is_now_city DESC,'.$insert_sort;
					$quanguo_name = $_FANWE['cache']['city']['all'][CHINA_CITY_PY]['name'];
					$where.=  " AND gk.city IN ('$city_name','$quanguo_name')";
				}
				else
				{
					$where.=  " AND gk.city = '$city_name'";
				}
			}

            $where .= " AND gk.end_time <= ".TIME_UTC;

			$order = '';
			$sort = &$page_args['sort'];
			$sort_array = array('spa'=>'g.shop_price ASC','spd'=>'g.shop_price DESC','eta'=>'gk.end_time ASC','etd'=>'gk.end_time DESC','cca'=>'g.click_count ASC','ccd'=>'g.click_count DESC','sa'=>'g.score ASC','sd'=>'g.score DESC','ba'=>'g.bought ASC','bd'=>'g.bought DESC','da'=>'discount ASC','dd'=>'discount DESC');

			if(array_key_exists($sort,$sort_array))
				$order = $sort_array[$sort];
			else
			{
				unset($page_args['sort']);
				$sort = '';
			}

			if(empty($order))
				$order .= 'similarity DESC,'.$insert_sort.',gk.sort ASC,g.id ASC';
			else
				$order .= ',similarity DESC,'.$insert_sort.',gk.sort ASC,g.id DESC';

			$goods_count = DB::resultFirst('SELECT COUNT(DISTINCT g.id)
				FROM '.DB::table('goods_match').' AS gm
				INNER JOIN '.DB::table('goods_key').' AS gk ON gk.id = gm.id
				INNER JOIN '.DB::table('goods').' AS g ON g.id = gk.id '.$where);

			$pager = buildPage('goods/search',$page_args,$goods_count,$_FANWE['page'],24);

			$res = DB::query('SELECT g.id,g.small_img,g.end_time,g.market_price,g.begin_time,g.shop_price,
				gk.city,gk.site_id,g.is_best,g.bought,g.name,g.sort,g.site_name,g.collect_buy,g.click_count,
				g.url,g.collect_count,g.add_time,(g.shop_price / g.market_price) AS discount,g.post_count'.$fields.'
				FROM '.DB::table('goods_match').' AS gm
				INNER JOIN '.DB::table('goods_key').' AS gk ON gk.id = gm.id
				INNER JOIN '.DB::table('goods').' AS g ON g.id = gk.id '.$where.'
				ORDER BY '.$order.' LIMIT '.$pager['limit']);

			$goods_list = array();


			while($goods = DB::fetch($res))
			{
				S('Goods')->goodsFormat($goods);
				$goods_list[] = $goods;
			}
		}

		include template('page/search_index');

		display();
	}

	public function show()
	{
		global $_FANWE;
		$id = intval($_FANWE['request']['id']);
		if($id == 0)
			fHeader('location:./');

		if($_FANWE['setting']['goods_show_type'] == 0)
		{
			GoodsModule::go();
			return;
		}

		//用于网站评论的发表频率限制
		$key = $_FANWE['uid'].'_check_goods_message_'.$id;
		if(empty($_FANWE['cookie'][$key]))
			fSetCookie($key, authcode($_FANWE['client_ip']."\t0", 'ENCODE'),604800, 1, true);

		S("RankStatistic")->goods($id,'GOODS_CLICK');

		$spread = intval($_FANWE['request']['spread']);

		if($spread > 0)
			S('auction')->insertAuctionClick($id,$spread,'goods');

		$cache_args = array(
			$id,
		);

		$cache_file = getTplCache('page/goods_show',$cache_args);

		if(!@include($cache_file))
		{
			$goods = DB::fetchFirst('SELECT *,(shop_price / market_price) AS discount FROM '.DB::table('goods').' WHERE id = '.$id.' AND status = 1');

			if(!$goods)
				fHeader('location:./');

			$_FANWE['nav_title'] = $goods['name'];
			S('Goods')->goodsFormat($goods);
			$goods['site'] = $_FANWE['cache']['site']['all']['s_'.$goods['site_id']];

			$goods_detail = $goods;
			$goods_detail['site_url'] = $goods['site']['url'];
			$goods_detail['site_name'] = $goods['site']['name'];

			unset($goods_detail['site']);
			unset($goods_detail['thread_id']);
			unset($goods_detail['brief']);
			unset($goods_detail['status']);
			unset($goods_detail['sort']);
			unset($goods_detail['add_time']);
			unset($goods_detail['update_time']);
			unset($goods_detail['content']);
			unset($goods_detail['sale_price']);
			unset($goods_detail['sale_key']);
			unset($goods_detail['collect_key']);
			unset($goods_detail['collect_url']);
			unset($goods_detail['collect_name']);
			unset($goods_detail['post_count']);
			$goods_detail = base64_encode(serialize($goods_detail));
			include template('page/goods_show');
		}

		display($cache_file);
	}

	public function go()
	{
		global $_FANWE;

		$id = intval($_FANWE['request']['id']);
		if($id == 0)
			fHeader('location:./');

		$spread = intval($_FANWE['request']['spread']);

		if($spread > 0)
			S('auction')->insertAuctionClick($id,$spread,'goods');

		$goods = DB::fetchFirst('SELECT * FROM '.DB::table('goods').' WHERE id = '.$id.' AND status = 1');

		if(isset($goods['url']) && !empty($goods['url']))
		{
			$_FANWE['nav_title'] = $goods['name'];
			S("RankStatistic")->goods($id,'GOODS_CLICK');

			$url = $goods['url'];

			$urls = "";

			$site = $_FANWE['cache']['site']['all']['s_'.$goods['site_id']];

			if(!empty($site['cps_url']))
				fHeader('location: '.$site['cps_url'].$goods['url']);

			if(!empty($site['invite_url']))
				fHeader('location: '.$site['invite_url']);

			if(!empty($site['code_position']))
			{
				$arr = explode('[CODE]',$site['code_position']);
				$urls = array();

				if($arr[1] != '')
				{
					$reg = str_replace('.', '\.',$arr[1]);
					preg_match("/(.*?)(".$reg.")/si",$url,$matches);
					$urls[0] = $matches[1];
					$urls[1] = $matches[2];
				}
				else
				{
					$urls[0] = $url;
					$urls[1] = "";
				}

				if(!empty($site['invite_key']))
					$urls[0].= $site['invite_key'];

				if(!empty($sale_key))
					$urls[0].= $sale_key;

				$url = $urls[0].$urls[1];
			}

			fHeader('location:'.$url);
		}
		else
			fHeader('location:./');
	}

	private function getList($where='',$no_query = false)
	{
		global $_FANWE;

		if(!$no_query)
		{
			if(defined('IS_CACHE_TPL'))
				$fields = '';
			else
				$fields = ',g.post_count';

			$page_args = array(
				'city_py' => CURRENT_CITY_PY,
				'site' => intval($_FANWE['request']['site']),
				'cat' => intval($_FANWE['request']['cat']),
				'sort' => trim($_FANWE['request']['sort']),
				'date' => trim($_FANWE['request']['date']),
				'keyword' => trim($_FANWE['request']['keyword']),
				'prices' => trim($_FANWE['request']['prices']),
			);

			$site_id = 0;
			if($page_args['site'] > 0)
			{
				$site_id = $page_args['site'];
				$site_where = ' AND gk.site_id = '.$page_args['site'];
			}
			else
				unset($page_args['site']);

			$dates = S('Goods')->getExpiredGoodsDate();

			$min_time = getTodayTime();
            $max_time = TIME_UTC;
            $date = toDate($min_time,'Y-m-d');

			if(!empty($page_args['date']))
			{
				$time = str2Time($page_args['date']);
				if($time <= $dates['max_time'] && $time >= $dates['min_time'])
				{
					$date = toDate($time,'Y-m-d');
					$min_time = str2Time(toDate($time,'Y-m-d'));
					$max_time = $min_time + 86399;
                    if($max_time > TIME_UTC)
                        $max_time = TIME_UTC;
				}
			}
			else
			{
                $page_args['date'] = $date;
			}

			$dates['min_time'] = toDate($dates['min_time'],'r');
			$dates['max_time'] = toDate($dates['max_time'],'r');

      		$where.=" AND gk.end_time >= '$min_time' AND gk.end_time <= '$max_time'";

			$keyword = '';
			if($page_args['keyword'] != '')
			{
				$page_args['keyword'] = urldecode($page_args['keyword']);
				$keyword = &$page_args['keyword'];
				$keyword_query = mysqlLikeQuote($page_args['keyword']);
				$where.=" AND (g.name LIKE '%$keyword_query%')";
			}
			else
				unset($page_args['keyword']);

			$insert_sort = 'gk.cr_sort ASC';

			if($page_args['cat'] > 0)
				$insert_sort = 'gk.ec_sort ASC';

			if(in_array($page_args['cat'],$_FANWE['cache']['goods']['root_cates']))
				$insert_sort = 'gk.dc_sort ASC';


			$city_name = $_FANWE['current_city']['name'];

			if(CURRENT_CITY_PY == CHINA_CITY_PY)
			{
				//全国不包含所有城市商品时
				if($_FANWE['setting']['all_city'] == 0)
					$where.=  " AND gk.city = '$city_name'";
				else
				{
					$insert_sort = 'gk.r_sort ASC';

					if($page_args['cat'] > 0)
						$insert_sort = 'gk.e_sort ASC';

					if(in_array($page_args['cat'],$_FANWE['cache']['goods']['root_cates']))
						$insert_sort = 'gk.d_sort ASC';
				}
			}
			elseif(CURRENT_CITY_PY != '')
			{
				//城市显示全国商品时
				if($_FANWE['setting']['index_all'] == 1)
				{
					$fields .= ",(gk.city = '$city_name') as is_now_city";
					$insert_sort = 'is_now_city DESC,'.$insert_sort;
					$quanguo_name = $_FANWE['cache']['city']['all'][CHINA_CITY_PY]['name'];
					$where.=  " AND gk.city IN ('$city_name','$quanguo_name')";
				}
				else
				{
					$where.=  " AND gk.city = '$city_name'";
				}
			}

			//价格条件
			$prices = '';
			if(!empty($page_args['prices']))
			{
				$prices = &$page_args['prices'];
				$price_arr = explode(',',$prices);
				$price_min = intval($price_arr[0]);
				$price_max = intval($price_arr[1]);

				if($price_min > 0)
					$where.=" AND (g.shop_price >= $price_min)";

				if($price_max > 0)
					$where.=" AND (g.shop_price <= $price_max)";
			}
			else
				unset($page_args['prices']);

			$goods_cates = S('Goods')->getExpiredGoodsCats($site_where.$where);

			$cate_id = 0;
			if($page_args['cat'] > 0)
			{
				$cate_id = &$page_args['cat'];
				$cateobj = $_FANWE['cache']['goods']['cats'][$cate_id];
				$cate_ids = array();
				if(isset($cateobj['childs']))
					$cate_ids = $cateobj['childs'];

				$cate_ids[] = $cate_id;

				if(count($cate_ids) > 1)
					$where.=' AND gk.cate_id IN ('.implode(',', $cate_ids).')';
				else
					$where.=" AND gk.cate_id = '$cate_id'";
			}
			else
				unset($page_args['cat']);

			$goods_sites = S('Goods')->getExpiredGoodsSites($where);

			$where = $site_where.$where;

			$order = '';
			$sort = &$page_args['sort'];
			$sort_array = array('spa'=>'g.shop_price ASC','spd'=>'g.shop_price DESC','eta'=>'g.end_time ASC','etd'=>'g.end_time DESC','cca'=>'g.click_count ASC','ccd'=>'g.click_count DESC','sa'=>'g.score ASC','sd'=>'g.score DESC','ba'=>'g.bought ASC','bd'=>'g.bought DESC','da'=>'discount ASC','dd'=>'discount DESC');

			if(array_key_exists($sort,$sort_array))
				$order = $sort_array[$sort];
			else
			{
				unset($page_args['sort']);
				$sort = '';
			}

			if(empty($order))
				$order .= 'g.is_best DESC,'.$insert_sort.',g.sort ASC,g.id ASC';
			else
				$order .= ','.$insert_sort.',g.sort ASC,g.id DESC';

			$goods_count = S('Goods')->getExpiredGoodsCount($where);

			$pager = buildPage('goods/'.ACTION_NAME,$page_args,$goods_count,$_FANWE['page'],15);
			$goods_result = S('Goods')->getExpiredGoodsList($where,$order,$fields,$pager['limit']);
			$goods_result['ids'] = implode(',',$goods_result['ids']);
		}

		include template('page/goods_index');
	}
}
?>